package com.hejun.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hejun.security.dao.UserinfoMapper;
import com.hejun.security.domain.Role;
import com.hejun.security.domain.Userinfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class UserService extends ServiceImpl<UserinfoMapper,Userinfo> implements UserDetailsService {

    @Autowired
    UserinfoMapper userMapper;

    @Autowired
    PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LambdaQueryWrapper<Userinfo> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Userinfo::getUname,username);
        List<Userinfo> userinfos = userMapper.selectList(queryWrapper);

        if (userinfos==null||userinfos.size()==0){
            throw new UsernameNotFoundException("账户不存在");
        }

        Userinfo userinfo=userinfos.get(0);
        userinfo.setRoles(userMapper.getRolesByUserId(userinfo.getId()));

        Collection<GrantedAuthority> collection=new ArrayList<>();
        for (Role role : userinfo.getRoles()) {
            //取出用户的权限，重新封装到security提供的Role里面
            collection.add(new SimpleGrantedAuthority(role.getRoleName()));

            /*
            for (Menu menu : role.getMens()) {
                //权限精准到菜单栏的时候需要这个for循环，实际上，角色权限和菜单栏权限有一个满足就可以访问相关资源
                collection.add(new SimpleGrantedAuthority(menu.getMCode()));
            }
            *
             */
        }

        UserDetails userDetails=new User(
                userinfo.getUname(),
                userinfo.getPwd(),
                collection);

        return userDetails;
    }
}
